//
//  CBCReadPageViewController.m
//  CBCReader
//
//  Created by Labanotation on 16/5/30.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "CBCReadPageViewController.h"
#import "CBCReadViewController.h"
#import "CBCChapterModel.h"
#import "CBCMenuView.h"
#import "CBCCatalogViewController.h"
#import "UIImage+ImageEffects.h"
#import "CBCNoteModel.h"
#import "CBCMarkModel.h"
#import <objc/runtime.h>
#import "CBCStream.h"
#import "JCDownloader.h"
#import "JCDownloadOperation.h"
#import "CBCReadConfig.h"
//#import "ShareView.h"
#import "CBCCatalogViewController.h"
#import "CBCReaderDef.h"
#import "CBCProgressHUD+Add.h"
//#import "NSObject+Category.h"
//#import "BookshelfTools.h"
#define AnimationDelay 0.3
#import "CBCReadingMaskingView.h"
#import "BookInfo.h"
#import "CommonFuctions.h"
#import "CBCReadTools.h"
//#import "CBCContentViewController.h"

@interface CBCReadPageViewController ()<UIPageViewControllerDelegate,UIPageViewControllerDataSource,CBCMenuViewDelegate,UIGestureRecognizerDelegate,CBCCatalogViewControllerDelegate>
{
    NSUInteger _chapter;    //当前显示的章节
    NSUInteger _chapterChange;  //将要变化的章节
    NSUInteger _pageChange;     //将要变化的页数
    NSUInteger _page;
}
@property (nonatomic,strong) UIPageViewController *pageViewController;
@property (nonatomic,getter=isShowBar) BOOL showBar; //是否显示状态栏
@property (nonatomic,strong) CBCMenuView *menuView; //菜单栏
@property (nonatomic,strong) CBCCatalogViewController *catalogVC;   //侧边栏
@property (nonatomic,strong) CBCReadViewController *readView;   //当前阅读视图
@property (nonatomic,assign) NSUInteger  page;
@property (nonatomic,assign) BOOL didAppear;//页面是否已经显示
@property (nonatomic,assign) BOOL isTrasnFromBefore;//是否是向前翻页
@property (nonatomic,strong) CBCReadingMaskingView * maskView;
@property (nonatomic,strong) CBCReadModel *model;
@property (nonatomic,assign) NSInteger chapterNum;
@property (nonatomic,strong) UITapGestureRecognizer * tap;
@property (nonatomic,assign)BOOL hasShowRecommad;
@property (nonatomic,assign)BOOL gesChapterChanged;//如果是手势切换的章节
@property (nonatomic,assign)BOOL isNavigaionHidden;
@end

@implementation CBCReadPageViewController

-(id)initWithReadModel:(CBCReadModel *)readModel{
    if(self = [super init]){
        self.model = readModel;
        self.didAppear = NO;
        self.chapterIndex =  -1;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self addChildViewController:self.pageViewController];
    [self checkCacheAndInitData];//先检测是否有缓存
    [self initReadControllers];
    [self makeViewGesture];
    [self.view addSubview:self.menuView];
    [self checkMaskingView];
    _isNavigaionHidden = self.navigationController.navigationBar.hidden;
}


//
-(void)initReadControllers{
    
    if (![self checkchapterhasdownforindex:_chapterNum]) {
        UIViewController * control =  [self makeHolderReadViewWithReadType:readResultLoading];
        [self setviewControllers:@[control] Animated:NO Direction:self.isTrasnFromBefore];
        [self downloadChatpterWithIndex:_chapterNum];
    }else{
        UIViewController * control = [self readViewWithChapter:_chapterChange page:_pageChange];
        [self setviewControllers:@[control] Animated:NO Direction:YES];
    }
    [self preloadChapterWithChapterIndex:_chapterChange+1];
    [self preloadChapterWithChapterIndex:_chapterChange-1];
//    [BookshelfTools makeReadModelTolike:self.model];
}

-(void)makeViewGesture{
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showToolMenu)];
    tap.delegate = self;
    _tap = tap;
    [self.view addGestureRecognizer:tap];
}

//检测是否添加提示蒙版
-(void)checkMaskingView{
    BOOL open =  [[NSUserDefaults standardUserDefaults]boolForKey:ReadOpenNotFirst];
    if (!open) {
        [self.view addSubview:self.maskView];
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:ReadOpenNotFirst];
    }
}


/**
 设置当前阅读页面

 @param controllers 阅读的控制器
 @param animated 是否有翻页动画
 @param leftToright 是否向后翻页。否则向前翻页，决定动画方向
 */
-(void)setviewControllers:(NSArray*)controllers Animated:(BOOL)animated Direction:(BOOL)leftToright{
    
    [_pageViewController setViewControllers:controllers direction:(leftToright? UIPageViewControllerNavigationDirectionForward:UIPageViewControllerNavigationDirectionReverse) animated:animated completion:nil];
    [self updateReadModelWithChapter:_chapterChange page:_pageChange];
    
}

/**
 检测本地是否有缓存对象，并设定主model，初始化章节页数等信息
 */
-(void)checkCacheAndInitData{
    
    NSString * key =  _model.bookInfo.ID;
    NSData * data = [[NSUserDefaults standardUserDefaults] valueForKey:key];
    if (data) {
        NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        CBCReadModel * Rmodel = [unarchiver decodeObjectForKey:key];
        [unarchiver finishDecoding];
        if (Rmodel&&[Rmodel isMemberOfClass:[CBCReadModel class]]) {
            _model = Rmodel;
        }
    }
    if (!_model.record.chapterModel) {
        _model.record.chapterModel = _model.chapters.firstObject;
    }
    //用来判断是否从章节页面进入的
    if (self.chapterIndex >= 0) {
        _model.record.chapterModel = _model.chapters[self.chapterIndex];
        _chapterChange = self.chapterIndex;
        _pageChange = 0;
    }else{
        _chapterChange = _model.record.chapter;//数组的index
        _pageChange    = _model.record.page;  //页数的index
    }
    _page = _pageChange;
    _chapter = _chapterChange;
    _chapterNum = _model.record.chapterModel.num;//标志章节的index
    
}


//显示控制菜单
-(void)showToolMenu{
    BOOL isMarked = FALSE;
    CGFloat currentProgress = ((CGFloat)_pageChange/ (_model.record.chapterModel.pageCount>0?_model.record.chapterModel.pageCount:1));
    if (currentProgress>1) {
        currentProgress = 1;
    }
    [_readView.readView cancelSelected];
    isMarked?(_menuView.topView.state=1): (_menuView.topView.state=0);
    self.menuView.currentProgress = currentProgress;
    self.menuView.recordModel = _model.record;
    [self.menuView showAnimation:YES];
}


#pragma mark - init

#pragma mark - CatalogViewController Delegate

//章节控制器，选择章节结束的回调
-(void)catalog:(CBCCatalogViewController *)catalog didSelectChapter:(NSUInteger)chapter page:(NSUInteger)page{
    
    if (chapter==_chapterChange) {
        return;
    }
    self.isTrasnFromBefore = NO;
    _chapterChange = chapter;
    _pageChange    = page;
    CBCChapterModel * chapterModel = _model.chapters[_chapterChange];
    _chapterNum    = chapterModel.num;
    [self preloadChapterWithChapterIndex:_chapterChange+1];
    [self preloadChapterWithChapterIndex:_chapterChange-1];
    if (![self checkchapterhasdownforindex:_chapterNum]) {
        [self downloadChatpterWithIndex:_chapterNum];
    }else{
        UIViewController * control = [self readViewWithChapter:_chapterChange page:page];
        [self setviewControllers:@[control] Animated:NO Direction:self.isTrasnFromBefore];
        
    }
    [catalog.navigationController popViewControllerAnimated:YES];
    
}


//跳转章节，页数
-(void)jumpToChapter:(NSUInteger)chapter page:(NSUInteger)page{
    self.isTrasnFromBefore = page>_pageChange;
    _chapterChange = chapter;
    _pageChange    = page;
    CBCChapterModel * chapterModel = _model.chapters[_chapterChange];
    _chapterNum    = chapterModel.num;
 
    if (![self checkchapterhasdownforindex:_chapterNum]) {
        [self downloadChatpterWithIndex:_chapterNum];
    }else{
        NSMutableArray * reads = [NSMutableArray arrayWithCapacity:1];
        UIViewController * control = [self readViewWithChapter:_chapterChange page:page];
        if (control) {
            [reads addObject:control];
        }
        [self setviewControllers:reads Animated:YES Direction:self.isTrasnFromBefore];
    }
}

#pragma mark -  UIGestureRecognizer Delegate
//解决TabView与Tap手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"CBCReadView"]) {
        return YES;
    }
    
    return  NO;
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (gestureRecognizer==_tap) {
        CGPoint point =  [gestureRecognizer locationInView:self.view];
        if(point.x<self.view.frame.size.width*0.33){
            UIViewController * control = [self pageViewController:self.pageViewController viewControllerBeforeViewController:self];
            if(control){
                [self setviewControllers:@[control] Animated:YES Direction:NO];
            }
            return NO;
        }
        else if(point.x>self.view.frame.size.width*0.67){
            UIViewController * control = [self pageViewController:self.pageViewController viewControllerAfterViewController:self];
            if(control){
                [self setviewControllers:@[control] Animated:YES Direction:YES];
            }
            return NO;
        }
        return YES;
    }else{
        return NO;
    }
    
}


//预加载书籍
-(void)preloadChapterWithUrl:(NSString*)url donwloadPath:(NSString *)donwloadPath  completionBlock:(JCDownloadCompletionBlock)completionBlock{
    JCDownloadItem *item = [[JCDownloadItem alloc] init];
    item.groupId = [url lastPathComponent];
    item.downloadUrl = url;
    item.downloadFilePath = donwloadPath;
    JCDownloadOperation *operation = [JCDownloadOperation operationWithItem:item];
    [operation startWithProgressBlock:nil completionBlock:^(NSURL *filePath, NSError *error) {
        completionBlock(filePath,error);
    }];
    
}


-(void)startDownload:(NSString *)url donwloadPath:(NSString *)donwloadPath{
    JCDownloadItem *item = [[JCDownloadItem alloc] init];
    item.groupId = [url lastPathComponent];
    item.downloadUrl = url;
    item.downloadFilePath = donwloadPath;
    CBCProgressHUD * hud = [CBCProgressHUD showMessag:@"加载中..." toView:self.view];
    JCDownloadOperation *operation = [JCDownloadOperation operationWithItem:item];
    
    __weak typeof(self) weakSelf = self;
    [operation startWithProgressBlock:nil completionBlock:^(NSURL *filePath, NSError *error) {
        
        
        if (error) {
            [hud hideWithErrorWithMessage:error.localizedDescription];
            UIViewController * controller   = [weakSelf makeHolderReadViewWithReadType:NetworkError];
            [weakSelf setviewControllers:@[controller] Animated:NO Direction:self.isTrasnFromBefore];
        }else{
            NSMutableArray * reads = [NSMutableArray array];
            CBCChapterModel *chapterModel = _model.chapters[_chapterChange];
            _chapterNum = chapterModel.num;
            BOOL hasContent =  [weakSelf verifyCurrentChapterContent:chapterModel];
            if (hasContent) {
                if (self.isTrasnFromBefore) {
                    if (chapterModel.pageCount>0) {
                        _pageChange = chapterModel.pageCount - 1;
                        UIViewController * controller = [weakSelf readViewWithChapter:_chapterChange page: _pageChange];
                        [reads addObject:controller];
                    }else{
                        UIViewController * controller   = [weakSelf makeHolderReadViewWithReadType:NoContent];
                        [reads addObject:controller];
                    }
                }else{
                    UIViewController * controller = [weakSelf readViewWithChapter:_chapterChange page:0];
                    [reads addObject:controller];
                }
                
            }else{
                UIViewController * controller   = [weakSelf makeHolderReadViewWithReadType:NoContent];
                [reads addObject:controller];
            }
            [weakSelf setviewControllers:reads Animated:NO Direction:self.isTrasnFromBefore];
            hud.animationType = CBCProgressHUDAnimationFade;
            [hud hide:YES afterDelay:0.2];
        }
    }];
}

//添加占位视图
-(CBCReadViewController*)makeHolderReadViewWithReadType:(readResultType)type{
    CBCChapterModel * cmodel =  _model.chapters[_chapterChange];
    _readView = [[CBCReadViewController alloc] init];
    _readView.readType = type;
    _readView.chapterModel = cmodel;
    if (type==readResultLoading) {
        
    }else{
 
    }
    return _readView;
}

-(NSString *)getChapterContent:(NSUInteger)chapterNum bookID:(NSString *)bookID{
    
    NSString *filePath = [CBCReadTools getCBCZPath:[NSString stringWithFormat:@"%@_%lu.CBCZ",bookID,(unsigned long)chapterNum] andBookID:bookID];
    NSString *content = [[CBCStream sharedCBCStream] readCBCZfFileContent:filePath];
    return content;
}

#pragma mark - Menu View Delegate
-(void)menuViewDidHidden:(CBCMenuView *)menu
{
    _showBar = NO;
    [self setNeedsStatusBarAppearanceUpdate];
}

-(void)menuViewDidAppear:(CBCMenuView *)menu{
    _showBar = YES;
    [self setNeedsStatusBarAppearanceUpdate];
}



//滑动条拖动进度
-(void)menuViewChapterProgress:(CGFloat)progress{
    
    CBCChapterModel * chapter = _model.record.chapterModel;
    NSUInteger toIndex = floor(chapter.pageCount * progress);
    if (toIndex != _pageChange) {
        [self jumpToChapter:_chapterChange page:toIndex];
    }
}

//打开选择章节控制器
-(void)menuViewInvokeCatalog:(CBCBottomMenuView *)bottomMenu
{
    [_menuView hiddenAnimation:NO];
    CBCCatalogViewController *chapterVC = [[CBCCatalogViewController alloc]init];
    chapterVC.readModel = _model;
    chapterVC.delegate = self;
    self.isTrasnFromBefore = NO;
    [self.navigationController pushViewController:chapterVC animated:YES];
}


//选择章节结束的代理
-(void)menuViewJumpChapter:(NSUInteger)chapter page:(NSUInteger)page
{
    CBCChapterModel * cmodel = _model.chapters[chapter];
    _chapterNum = cmodel.num;
    _chapterChange = chapter;
    _pageChange = 0;
    [self preloadChapterWithChapterIndex:_chapterChange+1];
    [self preloadChapterWithChapterIndex:_chapterChange-1];
    if (![self checkchapterhasdownforindex:_chapterNum]) {
        [self downloadChatpterWithIndex:_chapterNum];
        [self updateReadModelWithChapter:_chapterChange page:_pageChange];
    }else{
        NSMutableArray * reads = [NSMutableArray arrayWithCapacity:1];
        UIViewController * control = [self readViewWithChapter:chapter page:_pageChange];
        if (control) {
            [reads addObject:control];
        }
        [self setviewControllers:reads Animated:NO Direction:YES];
    }
    
}


//字体大小改变的代理事件
-(void)menuViewFontSize:(CBCBottomMenuView *)bottomMenu{

    [_model.record.chapterModel updateFont];
    
    NSInteger pageIndex = (_model.record.page>_model.record.chapterModel.pageCount-1)?_model.record.chapterModel.pageCount-1:_model.record.page;
    _pageChange = pageIndex;
    NSMutableArray * reads = [NSMutableArray arrayWithCapacity:1];
    UIViewController * control = [self readViewWithChapter:_chapterChange page:pageIndex];
    if (control) {
        [reads addObject:control];
    }
    [self setviewControllers:reads Animated:NO Direction:YES];
    
}

//顶部菜单返回
-(void)menuViewBack:(CBCTopMenuView *)topMenu{
    //判断是否在书架中
    if([_dataSource respondsToSelector:@selector(isBookInBookShelf)]){
        BOOL isInBookShelf = [_dataSource isBookInBookShelf];
        if(isInBookShelf){
            [self.navigationController popViewControllerAnimated:YES];
        }
        else{
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"加入书架吧！" message:@"喜欢本书就加入书架吧，下次阅读更方便！" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction * cancle = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                if([_delegate respondsToSelector:@selector(addCurrentBookToBookShelf)]){
                    [_delegate addCurrentBookToBookShelf];
                }
//                [BookshelfTools saveReadModel:self.model];
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
            UIAlertAction * sure = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
                
            }];
            [alert addAction:cancle];
            [alert addAction:sure];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    else{
        [self.navigationController popViewControllerAnimated:YES];
    }


}
//顶部菜单分享
-(void)menuViewShare:(CBCTopMenuView *)topMenu{
    if([_delegate respondsToSelector:@selector(didTapShare)]){
        [_delegate didTapShare];
    }
}

#pragma mark - Create Read View Controller

//根据章节和页数返回阅读页面
-(CBCReadViewController *)readViewWithChapter:(NSUInteger)chapter page:(NSUInteger)page{
    _readView = [[CBCReadViewController alloc] init];
    _readView.recordModel = _model.record;
    CBCChapterModel *chapterModel = _model.chapters[chapter];
    BOOL success = [self verifyCurrentChapterContent:chapterModel];
    if (_model.record.chapter != chapter) {
        if(success){
            [chapterModel updateFont];
            if (self.gesChapterChanged) {
                if (_isTrasnFromBefore) {
                    _pageChange = chapterModel.pageCount -1;
                }else{
                    _pageChange = 0;
                }
            }else{
                _pageChange = page;
            }
            _readView.content = [chapterModel stringOfPage:_pageChange];
            _readView.page  = [NSString stringWithFormat:@"%zd/%zd",_pageChange+1,chapterModel.pageCount];
            _readView.chapterModel = chapterModel;
        }else{
            _readView.readType = NoContent;
            _readView.chapterModel = chapterModel;
        }
    }else{
        _readView.chapterModel = chapterModel;
        if (_pageChange>=_model.record.chapterModel.pageCount) {
            _pageChange = _model.record.chapterModel.pageCount -1;
        }
        _readView.content = [_model.record.chapterModel stringOfPage:_pageChange];
        _readView.page  = [NSString stringWithFormat:@"%zd/%zd",_pageChange+1,_model.record.chapterModel.pageCount];
    }
    return _readView;
}

//校验章节对象中是否有文本内容加载
-(BOOL)verifyCurrentChapterContent:(CBCChapterModel *)chapterModel{

    if ([CommonFuctions isBlankString:chapterModel.content]) {
        NSString * content = [self getChapterContent:chapterModel.num bookID:_model.bookInfo.ID];
        if ([CommonFuctions isBlankString:content]) {
            return NO;
        }
        chapterModel.content = content;
    }
    return YES;
    
}

//更新本地保存章节信息
-(void)updateReadModelWithChapter:(NSUInteger)chapter page:(NSUInteger)page{
    _chapter = chapter;
    _page = page;
    _model.record.chapterModel = _model.chapters[chapter];
    _model.record.chapter = chapter;
    _model.record.page = page;
    _model.font = [NSNumber numberWithFloat:[CBCReadConfig shareInstance].fontSize];
    [CBCReadModel updateLocalModel:_model key:_model.bookInfo.ID];
}

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers
{
    _chapter = _chapterChange;
    _page = _pageChange;
}

//检查指定的章节是否已经下载
-(BOOL)checkchapterhasdownforindex:(NSInteger)index{
    
    NSString *filePath = [CBCReadTools getCBCZPath:[NSString stringWithFormat:@"%@_%zd.CBCZ",_model.bookInfo.ID,index] andBookID:_model.bookInfo.ID];
    return [[NSFileManager defaultManager]fileExistsAtPath:filePath];
    
}
//下载指定的章节
-(void)downloadChatpterWithIndex:(NSInteger)chapterNum{
    
    NSString *filePath = [CBCReadTools getCBCZPath:[NSString stringWithFormat:@"%@_%zd.CBCZ",_model.bookInfo.ID,chapterNum] andBookID:_model.bookInfo.ID];
    //如果没有下载完成，那么开启网路下载
    NSString *url = [CBCReadTools getChapterFileUrl:chapterNum andBookID:_model.bookInfo.ID];
    [self startDownload:url donwloadPath:filePath];
    
}

#pragma mark -PageViewController DataSource

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    _pageChange = _page;
    _chapterChange = _chapter;

    self.isTrasnFromBefore = YES;
    if (_chapterChange==0 &&_pageChange == 0) {
        [CBCProgressHUD showMiddleHint:@"已是第一页"];
        return nil;
    }
    CBCChapterModel * chapter = _model.chapters[_chapterChange];

    if (_pageChange==0||chapter.pageCount==0) {
        if (_chapterChange==0) {
            [CBCProgressHUD showMiddleHint:@"已是第一章节"];
            return nil;
        }
        _chapterChange--;
        self.gesChapterChanged = YES;
        CBCChapterModel * preChapter = _model.chapters[_chapterChange];
        _chapterNum = preChapter.num;
        [self preloadChapterWithChapterIndex:_chapterChange-1];//预加载
        if (![self checkchapterhasdownforindex:_chapterNum]) {
            [self downloadChatpterWithIndex:_chapterNum];
            return nil;
        }
        _pageChange = preChapter.pageCount -1;
        
    }
    else{
        self.gesChapterChanged = NO;
        _pageChange--;
    }
    return [self readViewWithChapter:_chapterChange page:_pageChange];
    
}

-(void)preloadChapterWithChapterIndex:(NSInteger)Index{
    if (Index<0 || Index+1>_model.chapters.count) {
        return;
    }
    CBCChapterModel * preChapter = _model.chapters[Index];
    if (![self checkchapterhasdownforindex:preChapter.num]) {
        NSString *filePath = [CBCReadTools getCBCZPath:[NSString stringWithFormat:@"%@_%lu.CBCZ",_model.bookInfo.ID,(unsigned long)preChapter.num] andBookID:_model.bookInfo.ID];
        //如果没有下载完成，那么开启网路下载
        __weak typeof(self)weakSelf = self;
        NSString *url = [CBCReadTools getChapterFileUrl:preChapter.num andBookID:_model.bookInfo.ID];
        [self preloadChapterWithUrl:url donwloadPath:filePath completionBlock:^(NSURL *filePath, NSError *error) {
            CBCChapterModel *chapterModel = _model.chapters[Index];
            [weakSelf verifyCurrentChapterContent:chapterModel];
        }];
    }
}

- (nullable UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController{
    _pageChange = _page;
    _chapterChange = _chapter;
    self.isTrasnFromBefore = NO;
    if (_pageChange >= _model.chapters.lastObject.pageCount-1 && _chapterChange >= _model.chapters.count-1) {
        [self pushRecommandController];
        return nil;
    }
    CBCChapterModel * cmodel = _model.chapters[_chapterChange];
    
    if (_pageChange >= cmodel.pageCount-1||cmodel.pageCount == 0) {
        if (_chapterChange+1>=_model.chapters.count) {
            [CBCProgressHUD showMiddleHint:@"已是最后章节"];
            return nil;
        }
        _chapterChange++;
        self.gesChapterChanged = YES;
        _pageChange = 0;
        [self preloadChapterWithChapterIndex:_chapterChange+1];//预加载
        CBCChapterModel * nextModel = _model.chapters[_chapterChange];
        _chapterNum = nextModel.num;
        if (![self checkchapterhasdownforindex:_chapterNum]) {
            [self downloadChatpterWithIndex:_chapterNum];
            return nil;
        }
    }
    else{
        self.gesChapterChanged = NO;
        _pageChange++;
        
    }
    return [self readViewWithChapter:_chapterChange page:_pageChange];
}
//阅读完毕以后点击进入推荐页面
-(void)pushRecommandController{
    if([_delegate respondsToSelector:@selector(didFinishReading)]){
        [_delegate didFinishReading];
    }
}
#pragma mark -PageViewController Delegate
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed{
    if (!completed) {
        
        CBCReadViewController *readView = previousViewControllers.firstObject;
        _readView = readView;
        _page    = readView.recordModel.page;
        _chapter = readView.recordModel.chapter;
    }else{
       [self updateReadModelWithChapter:_chapter page:_page];
    }
    
}


#pragma mark =================控制电池栏===================

-(BOOL)prefersStatusBarHidden{
    if (self.didAppear) {
        return !_showBar;
    }
    return NO;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return  UIStatusBarStyleLightContent;
}

-(UIStatusBarAnimation)preferredStatusBarUpdateAnimation{
    
    return UIStatusBarAnimationFade;
}
-(void)viewDidAppear:(BOOL)animated{
    self.didAppear = YES;
    [self setNeedsStatusBarAppearanceUpdate];
}

-(void)viewWillAppear:(BOOL)animated{
    self.hasShowRecommad = NO;
    if(_isNavigaionHidden == false){
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    self.didAppear = NO;
    [self setNeedsStatusBarAppearanceUpdate];
    if(_isNavigaionHidden == false){
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
}


#pragma mark ==================  懒加载对象=======================
-(CBCReadingMaskingView *)maskView{
    if (!_maskView) {
        _maskView = [[CBCReadingMaskingView alloc]initWithFrame:self.view.bounds];
    }
    return _maskView;
}
-(CBCMenuView *)menuView{
    if (!_menuView) {
        _menuView = [[CBCMenuView alloc] initWithFrame:self.view.bounds];
        _menuView.hidden = YES;
        _menuView.delegate = self;
        _menuView.recordModel = _model.record;
        _menuView.isHiddenShare = _isHiddenShare;
    }
    return _menuView;
}
-(UIPageViewController *)pageViewController{
    if (!_pageViewController) {
        _pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStylePageCurl navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
        _pageViewController.delegate = self;
        _pageViewController.dataSource = self;
        [self.view addSubview:_pageViewController.view];
        for(UITapGestureRecognizer *gestrue in self.pageViewController.gestureRecognizers){
            if([gestrue isKindOfClass:[UITapGestureRecognizer class]]){
                gestrue.delegate = self;

            }
        }
    }
    return _pageViewController;
}

-(CBCCatalogViewController *)catalogVC{
    if (!_catalogVC) {
        _catalogVC = [[CBCCatalogViewController alloc] init];
        _catalogVC.readModel = _model;
        _catalogVC.delegate = self;
    }
    return _catalogVC;
}
@end
